const { UNKNOWN_ERROR } = require("../config/error-constants");
const fileService = require("../service/file.service");
const userService = require("../service/user.service");
const { to } = require("../utils");
const { SERVER_HOST, SERVER_PORT } = require("../config/server");
class FileController {
    async uploadAvatar(ctx, next) {
        const { filename, size, mimetype } = ctx.request.file;
        const { id } = ctx.user;
        const [error, resp] = await to(fileService.uploadAvatar(filename, mimetype, size, id));
        if (error) {
            return ctx.app.emit("error", UNKNOWN_ERROR, ctx);
        }
        const avatarUrl = `${SERVER_HOST}:${SERVER_PORT}/users/avatar/${id}`;
        // 更新用户头像
        const [updateAvatarError, updateAvatarResp] = await to(userService.updateAvatarUrl(avatarUrl, id));
        if (updateAvatarError) {
            return ctx.app.emit("error", UNKNOWN_ERROR, ctx);
        }
        ctx.body = "头像上传成功~";
    }
}

module.exports = new FileController();
